import React, { useState } from 'react';
import axios from 'axios';
import { Row, Col, Button, message } from 'antd';
import { useHistory } from 'react-router-dom';
import DeviceSetting from './DeviceSetting';
import { useEffectOnce } from '../../utils/hooks';

export interface Device {
  deviceName: string;
  dacNames: string[];
  maxPointsInDynamicGraph: number;
  detailedPointsCount: number;
  detailedPointsMoveSteps: number;
}
const DeviceManagement = () => {
  const defaultMaxPointsInDynamicGraph = 200;
  const defaultDetailedPointsCount = 100;
  const defaultDetailedPointsMoveSteps = 20;
  let [devices, setDevices] = useState([] as Device[]);
  let history = useHistory();

  useEffectOnce(() => {
    axios
      .get('/devices')
      .then((response) => {
        setDevices(response.data);
      })
      .catch((error) => {
        if (error.response?.status === 401) {
          message.error('请先登录！');
          history.replace('/login');
        }
      });
  });

  const removeDevice = (index: number) => {
    setDevices([...devices.slice(0, index), ...devices.slice(index + 1)]);
  };

  const handleDeviceSettingChange = (index: number, newDevice: Device) => {
    setDevices([...devices.slice(0, index), newDevice, ...devices.slice(index + 1)]);
  };

  const addDevice = () => {
    // 不能直接用push，会在原数组上修改，数组本身没发生变化导致不触发重新渲染
    setDevices([
      ...devices,
      {
        deviceName: '',
        dacNames: [],
        maxPointsInDynamicGraph: defaultMaxPointsInDynamicGraph,
        detailedPointsCount: defaultDetailedPointsCount,
        detailedPointsMoveSteps: defaultDetailedPointsMoveSteps
      }
    ]);
  };

  const checkDevice = (device: Device): boolean => {
    if (device.deviceName === '') {
      return false;
    }
    if (device.maxPointsInDynamicGraph <= 0) {
      return false;
    }
    if (device.detailedPointsCount <= 0) {
      return false;
    }
    if (device.detailedPointsMoveSteps <= 0) {
      return false;
    }
    return true;
  };

  const checkDuplicateDeviceName = (devices: Device[]): boolean => {
    let nameExistMap: Record<string, boolean> = {};
    for (let device of devices) {
      if (nameExistMap[device.deviceName] === undefined) {
        nameExistMap[device.deviceName] = true;
      } else {
        // 有重复名字
        return false;
      }
    }
    return true;
  };

  const saveDevices = () => {
    for (let device of devices) {
      if (!checkDevice(device)) {
        message.error('设备名称（不能为空）或者数据点（不能小于或等于0）设定存在问题，请检查！');
        return;
      }
    }
    if (!checkDuplicateDeviceName(devices)) {
      message.error('存在重复的设备名称，请检查！');
      return;
    }
    axios
      .post('/devices', devices)
      .then(() => {
        message.success('操作成功！');
        // 刷新页面使得导航中的设备名称对应改变
        window.location.reload();
      })
      .catch((error) => {
        if (error.response?.status === 401) {
          message.error('请先登录！');
          history.replace('/login');
        }
      });
  };

  return (
    <>
      {devices.map((device, index) => (
        <Row key={index.toString()} gutter={[0, 20]}>
          <Col span={10} offset={7}>
            <DeviceSetting
              index={index}
              setting={device}
              removeDevice={removeDevice}
              handleDeviceSettingChange={handleDeviceSettingChange}
              defaultMaxPointsInDynamicGraph={defaultMaxPointsInDynamicGraph}
              defaultDetailedPointsCount={defaultDetailedPointsCount}
              defaultDetailedPointsMoveSteps={defaultDetailedPointsMoveSteps}
            />
          </Col>
        </Row>
      ))}
      <Row gutter={[0, 20]}>
        <Col span={8} offset={8}>
          <Button onClick={addDevice} style={{ width: '100%' }}>
            + 新设备
          </Button>
        </Col>
      </Row>
      <Row gutter={[0, 20]}>
        <Col span={8} offset={8}>
          <Button type="primary" onClick={saveDevices} style={{ width: '100%' }}>
            保存
          </Button>
        </Col>
      </Row>
    </>
  );
};

export default DeviceManagement;
